//
//  TimelinePresenter.m
//  MVC|MVP|MVVM
//
//  Created by Guo Rui on 2017/11/14.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "TimelinePresenter.h"
#import "NSObject+Orientation.h"

@implementation TimelinePresenter

- (void)userLikeHandle
{
    self.model.like = !self.model.like;
    self.model.likeCount = self.model.like ? self.model.likeCount + 1 : self.model.likeCount - 1;
    
    [self.view setLike:self.model.like];
    [self.view setLikeCount:self.model.likeCount];
}

- (void)setView:(MVP_TableViewCell *)view
{
    _view = view;
    
    __weak typeof(self) _self = self;
    view.clickZan = ^{
        [_self userLikeHandle];
    };
    
    MediaModel *mediaModel = [self.model.mediaList firstObject];
    // 1. url
    [view setImageURL:mediaModel ? mediaModel.imgUrl : nil];
    
    if (mediaModel) {
        NSNumber *realW = mediaModel.w;
        NSNumber *realH = mediaModel.h;
        
        UIImageOrientation orientation = [self exifOrientationToIOSOrientation:mediaModel.imageOrientation];
        if (orientation == UIImageOrientationLeft || orientation == UIImageOrientationRight) {
            NSNumber *temp = realW;
            realW = realH;
            realH = temp;
        }
        
        CGFloat ratio = realW.floatValue / realH.floatValue;
        CGFloat w = 0;
        CGFloat h = 0;
        if (ratio >= 1) {
            w = 120;
            h = w * ratio;
        }
        else {
            h = 120;
            w = h / ratio;
        }
        CGSize size = CGSizeMake(w, h);
        
        [view updateImageViewConstraintWithSize:size];
        [view hiddenImageView:NO];
    }
    else {
        [view updateImageViewConstraintWithSize:CGSizeZero];
        [view hiddenImageView:YES];
    }
    
    // 2. content
    if (self.model.content == nil || self.model.content.length == 0) {
        [view setTimelineContent:nil];
        [view hiddenTimelineContentLabel:YES];
    }
    else {
        [view setTimelineContent:self.model.content];
        [view hiddenTimelineContentLabel:NO];
    }
    
    // 3. publishInfo
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *dotime = [fmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:self.model.date.floatValue / 1000]];
    [view setPublishInfo:[NSString stringWithFormat:@"%@发布于%@", self.model.author.relationName, dotime]];
    
    // 4. like
    [view setLike:self.model.like];
    [view setLikeCount:self.model.likeCount];
    
    // 5. comment
    [view setCommentCount:self.model.commentCount];
}

@end
